#include "reservehome.h"
#include "ui_reservehome.h"
#include "seatreserve.h"
#include "home.h"
#include "reserveannouncement.h"
#include "reservecheck.h"
#include "announcement.h"
#include "enteryandout.h"
#include "appeal.h"
#include "reminds.h"
#include <QDebug>
#include "QMouseEvent"
#include <QDateTime>
#include <QTimer>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <iostream>
#include <QMessageBox>
bool reserveHome::booked=false;
int reserveHome::index_campus = 0;
int reserveHome::index_floor = 0;
int reserveHome::index_area = 0;
int reserveHome::choice = 0;
QString reserveHome::history[999];
int reserveHome::historyNum = 0;
bool reserveHome::isMessageShowAgain = true;
bool reserveHome::isMessageShowAgain2 = true;
bool reserveHome::announcementIsHome = true;
bool reserveHome::isReserved = false ;
QString reserveHome::reserveTime = "";
bool reserveHome::isToday = true;
QTime reserveHome::enteryTime = QTime(0,0);
bool reserveHome::isEntery = false;
int reserveHome::breaktimes = 0;
bool reserveHome::isRemindShowAgain = true;

campus reserveHome::campuses[4] = {
    {"新校区", 7, nullptr},
    {"本部校区", 6, nullptr},
    {"铁道校区", 6, nullptr},
    {"湘雅新校区", 5, nullptr}
};

reserveHome::reserveHome(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::reserveHome)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint); // 设置窗口无边框
    e = new enteryandout;
    connect(e, SIGNAL(entry()), this, SLOT(entry()));
    connect(e, SIGNAL(out()), this, SLOT(out()));

    entryfirsttimer = new QTimer(this);
    connect(entryfirsttimer, &QTimer::timeout, this, &reserveHome::updateElapsedTime);

    elapsedTime = QTime(0,0);

    // 创建一个定时器，每1000毫秒（1秒）触发一次
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &reserveHome::updateCountdown);

    if(booked && !isEntery && breaktimes != 2 ){
        if(isToday){
            ui->label_2->setText("位置：\n"+campuses[index_campus].name+"-"+reserveHome::campuses[index_campus].f[index_floor].name+"-"+reserveHome::campuses[index_campus].f[index_floor].a[index_area].name+
                            "-"+campuses[index_campus].f[index_floor].a[index_area].s[choice].name+
                             "\n请在 " + reserveTime + " 之前签到");
            e->show();
        }else{
            ui->label_2->setText("位置：\n"+campuses[index_campus].name+"-"+reserveHome::campuses[index_campus].f[index_floor].name+"-"+reserveHome::campuses[index_campus].f[index_floor].a[index_area].name+
                                "-"+campuses[index_campus].f[index_floor].a[index_area].s[choice].name);
        }
        ui->label->setText("预约信息：");
        ui->pushButton_5->show();
        ui->pushButton_3->hide();
        if(!isToday){
            ui->label_11->setText("请在 "+reserveTime+" 前入馆");
        }else{
            QStringList list = reserveTime.split(" ");

            QTime current = QTime::currentTime();
            QString currentTimeString = current.toString("HH:mm:ss");

            // 将第一个时间字符串转换为QTime对象
            QTime requestTime = QTime::fromString(list.at(1), "HH:mm:ss");

            // 将当前时间字符串转换为QTime对象
            QTime currentTime = QTime::fromString(currentTimeString, "HH:mm:ss");
            // 计算两个时间的差值
            int diffInSeconds = currentTime.secsTo(requestTime);

            // 将差值转换为mm:ss格式
            int minutes = diffInSeconds / 60;
            int seconds = diffInSeconds % 60;

            QString timeDiff = QString("%1:%2").arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0'));

            ui->label_11->setText("入馆倒计时："+timeDiff);
            ui->label_11->setStyleSheet("QLabel { font-size: 20pt; }");
            timer->start(1000); // 启动定时器
        }
        ui->label_9->show();
        ui->label_11->show();
        ui->label_12->show();
    }else if(booked && isEntery&& breaktimes != 2){
        e->show();
        ui->pushButton_5->hide();
        ui->label->setText("座位使用情况");
        ui->pushButton_3->hide();
        QString content = "<ol style='margin-left: 20px;'>"
                          "<li>在馆内请保持安静</li>"
                          "<li>请勿在馆内使用大功率电器设备！</li>"
                          "<li>请勿携带电动车电池、易燃易爆危险物品入馆！</li>"
                          "</ol>";
        ui->label_11->setText(content);
        ui->label_11->show();
        ui->label_12->show();
        ui->label_9->show();
        ui->label_2->setText("");
        QTime current = QTime::currentTime();
        // 将 QTime 对象转换为从午夜开始的秒数
        int currentSeconds = current.hour() * 3600 + current.minute() * 60 + current.second();
        int enteryTimeSeconds = enteryTime.hour() * 3600 + enteryTime.minute() * 60 + enteryTime.second();
        // 计算两个时间的差值（确保结果是正数）
        int diffInSeconds = currentSeconds - enteryTimeSeconds;
        if (diffInSeconds < 0) {
            diffInSeconds += 24 * 3600; // 如果当前时间小于入馆时间，说明跨越了午夜
        }
        // 将秒数差值转换回 QTime 对象
        elapsedTime = QTime(0, 0).addSecs(diffInSeconds);
        entryfirsttimer->start(1000);
    }else if(breaktimes == 2){
        ui->label_2->setText("您当前处于禁用状态");
        ui->label->setText("");
        ui->pushButton_3->hide();
        ui->pushButton_5->hide();
        ui->label_11->hide();
        ui->label_12->hide();
        ui->label_9->hide();
        // 创建一个QPushButton对象
        QPushButton *button = new QPushButton("去申诉 >");
        button->resize(599,141);
        ui->horizontalLayout->addWidget(button);
         // 为按钮设置样式
        button->setStyleSheet(R"(
            QPushButton {
                color: black;
                border: 5px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                border-radius: 20px; /* 设置圆角半径为20像素 */
                padding: 10px; /* 内边距 */
            }
            QPushButton:hover {
                color: green; /* 鼠标悬停状态 */
                border: 5px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                border-radius: 20px; /* 设置圆角半径为20像素 */
            }
            QPushButton:pressed {
                color: red; /* 按钮被按下状态 */
                border: 5px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                border-radius: 20px; /* 设置圆角半径为20像素 */
            }
        )");
        connect(button, &QPushButton::clicked, this, &reserveHome::onButtonClicked);
        button->show();

    }
    else{
        ui->label_2->setText("暂无预约信息");
        ui->label->setText("请先预约空间");
        ui->pushButton_5->hide();
        ui->label_9->hide();
        ui->label_11->hide();
        ui->label_12->hide();
    }
}

void reserveHome::entry(){
   if(!isEntery){
       isEntery = true;
       QTime currentTime = QTime::currentTime();
       enteryTime = currentTime;
       ui->pushButton_5->hide();
       ui->label->setText("座位使用情况");
       ui->pushButton_3->hide();
       QString content = "<ol style='margin-left: 20px;'>"
                         "<li>在馆内请保持安静</li>"
                         "<li>请勿在馆内使用大功率电器设备！</li>"
                         "<li>请勿携带电动车电池、易燃易爆危险物品入馆！</li>"
                         "</ol>";
       ui->label_11->setText(content);
       ui->label_11->show();
       ui->label_12->show();
       ui->label_9->show();
       ui->label_2->setText("");
       timer->stop();
       entryfirsttimer->start(1000); // 启动定时器，每秒触发一次
       QString currentString = currentTime.toString("HH:mm:ss");
       QString historyString = "进入图书馆 时间：" + currentString;
       history[historyNum++] = historyString;
   }else{
       breaktimes ++;
       if(breaktimes==1){
           QTime currentTime = QTime::currentTime();
           QString currentString = currentTime.toString("HH:mm:ss");
           QString historyString = "违约 时间：" + currentString;
           history[historyNum++] = historyString;
           // 创建一个QMessageBox对象
           QMessageBox messageBox;
           messageBox.setWindowTitle("警告");
           messageBox.setText("您已违反约定，出馆未打卡就再次入馆\n是否现在进行申诉");

           // 设置消息类型
           messageBox.setIcon(QMessageBox::Warning);

           // 添加按钮并设置点击事件处理函数
           QPushButton *yesButton = messageBox.addButton(QMessageBox::Yes);
           QPushButton *noButton = messageBox.addButton(QMessageBox::No);

           // 为“Ok”按钮设置点击事件处理函数
           connect(yesButton, &QPushButton::clicked, [&]() {
               appeal* a = new appeal;
               a->show();
           });

           // 为“No”按钮设置点击事件处理函数
           connect(noButton, &QPushButton::clicked, [&]() {
               messageBox.accept();
           });

           // 显示消息框
           messageBox.exec();
       }else{
           QTime currentTime = QTime::currentTime();
           QString currentString = currentTime.toString("HH:mm:ss");
           QString historyString = "禁用 时间：" + currentString;
           history[historyNum++] = historyString;
           // 创建一个QMessageBox对象
           QMessageBox messageBox;
           messageBox.setWindowTitle("警告");
           messageBox.setText("您当日已违反约定两次\n今天内无法使用座位预约系统");

           // 设置消息类型
           messageBox.setIcon(QMessageBox::Warning);

           // 添加按钮并设置点击事件处理函数
           QPushButton *yesButton = messageBox.addButton(QMessageBox::Yes);

           // 为“Ok”按钮设置点击事件处理函数
           connect(yesButton, &QPushButton::clicked, [&]() {
               messageBox.accept();
           });

           // 显示消息框
           messageBox.exec();
           e->close();
           entryfirsttimer->stop();
           ui->label_2->setText("您当前处于禁用状态");
           ui->label->setText("");
           ui->pushButton_3->hide();
           ui->pushButton_5->hide();
           ui->label_11->hide();
           ui->label_12->hide();
           ui->label_9->hide();
           // 创建一个QPushButton对象
           QPushButton *button = new QPushButton("去申诉 >");
           button->resize(599,141);
           ui->horizontalLayout->addWidget(button);
            // 为按钮设置样式
           button->setStyleSheet(R"(
               QPushButton {
                   color: black;
                   border: 2px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                   border-radius: 20px; /* 设置圆角半径为20像素 */
                   padding: 10px; /* 内边距 */
               }
               QPushButton:hover {
                   color: green; /* 鼠标悬停状态 */
                   border: 2px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                   border-radius: 20px; /* 设置圆角半径为20像素 */
               }
               QPushButton:pressed {
                   color: red; /* 按钮被按下状态 */
                   border: 2px solid #e0ffff; /* 设置边框宽度和透明颜色 */
                   border-radius: 20px; /* 设置圆角半径为20像素 */
               }
           )");
           connect(button, &QPushButton::clicked, this, &reserveHome::onButtonClicked);
           button->show();

       }
   }
}

void reserveHome::out(){
    if(isEntery){
       e->close();
       entryfirsttimer->stop();
       //更新座位信息
       campuses[index_campus].f[index_floor].a[index_area].s[choice].isUnbooked=true;
       //将取消后的信息保存回文件
       reserveHome::saveCampusesToJson(reserveHome::campuses,"D:\\QtCode\\Library_System_1\\library_seats.json");
       isEntery = false;
       booked = false;
       ui->label_2->setText("您当前没有预约信息");
       ui->label->setText("请先预约空间");
       ui->pushButton_3->show();
       ui->pushButton_5->hide();
       ui->label_9->hide();
       ui->label_11->hide();
       ui->label_12->hide();
       QTime currentTime = QTime::currentTime();
       QString currentString = currentTime.toString("HH:mm:ss");
       QString historyString = "离开图书馆 时间：" + currentString;
       history[historyNum++] = historyString;
    }else{
        // 创建一个QMessageBox对象
        QMessageBox messageBox;
        messageBox.setWindowTitle("提示");
        messageBox.setText("您还未刷卡入馆");

        // 设置消息类型
        messageBox.setIcon(QMessageBox::Information);

        // 添加按钮并设置点击事件处理函数
        QPushButton *okButton = messageBox.addButton(QMessageBox::Ok);

        // 为“Ok”按钮设置点击事件处理函数
        connect(okButton, &QPushButton::clicked, [&]() {
            messageBox.accept();
        });
        // 显示消息框
        messageBox.exec();
    }
}

void reserveHome::onButtonClicked(){
    appeal* a = new appeal;
    a->show();
}

void reserveHome::updateElapsedTime() {
    // 增加计时器的时间（每次增加一秒）
    elapsedTime = elapsedTime.addSecs(1);

    // 更新显示的时间格式
    QString formattedTime = elapsedTime.toString("hh:mm:ss");

    // 在标签上显示新的时间
    ui->label_2->setText("位置：\n" + campuses[index_campus].name + "-" + reserveHome::campuses[index_campus].f[index_floor].name + "-" +
                         reserveHome::campuses[index_campus].f[index_floor].a[index_area].name + "-" +
                         campuses[index_campus].f[index_floor].a[index_area].s[choice].name + "\n您已使用 " + formattedTime);
}

reserveHome::~reserveHome()
{
    e->close();
    delete ui;
}

void reserveHome::updateCountdown() {
    static int diffInSeconds = 0; // 静态变量，用于存储倒计时的剩余秒数

    QStringList list = reserveTime.split(" ");
    QTime requestTime = QTime::fromString(list.at(1), "HH:mm:ss");
    QTime currentTime = QTime::currentTime();
    diffInSeconds = currentTime.secsTo(requestTime);

    if (diffInSeconds >= 0) {
        int minutes = diffInSeconds / 60;
        int seconds = diffInSeconds % 60;
        QString timeDiff = QString("%1:%2").arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0'));
        ui->label_11->setText("入馆倒计时："+timeDiff);
    } else {
        ui->label_11->setText("入馆倒计时：00:00");
        QTimer *timer = static_cast<QTimer*>(sender());
        timer->stop();
        delete timer; // 删除定时器
    }
}

void reserveHome::on_pushButton_3_clicked()
{
    this->hide();
    //更新座位信息
    reserveHome::importJsonToCampuses("D:\\QtCode\\Library_System_1\\library_seats.json",reserveHome::campuses);
    seatReserve *seatreserve=new seatReserve;
    seatreserve->show();
}

void reserveHome::on_pushButton_clicked()
{
    this->close();
    home* h=new home;
    h->show();
}

void reserveHome::on_pushButton_5_clicked()
{
    // 获取当前的日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 格式化日期和时间
    QString dateTimeString = currentDateTime.toString("yyyy-MM-dd HH:mm:ss");
    QStringList list = reserveHome::history[historyNum-1].split(" ");
    // 构建字符串
    QString itemText;
    itemText += "取消预约 " + list.at(0) + " 操作时间："
            + dateTimeString;
    history[historyNum++] = itemText;
    ui->label_2->setText("您当前没有预约信息");
    ui->label->setText("请先预约空间");
    ui->pushButton_5->hide();
    ui->pushButton_3->show();
    ui->label_9->hide();
    ui->label_11->hide();
    ui->label_12->hide();
    e->close();
    entryfirsttimer->stop();
    //
    campuses[index_campus].f[index_floor].a[index_area].s[choice].isUnbooked=true;
    //将取消后的信息保存回文件
    reserveHome::saveCampusesToJson(reserveHome::campuses,"D:\\QtCode\\Library_System_1\\library_seats.json");
    booked=false;

}

void reserveHome::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
                initialMousePosition = event->globalPos(); // 记录鼠标按下时的全局位置
                isDragging = true; // 开始拖动
            }
    }

void reserveHome::mouseMoveEvent(QMouseEvent *event){
    if (isDragging && event->buttons() & Qt::LeftButton) {
                QPoint delta = event->globalPos() - initialMousePosition; // 计算鼠标移动的距离
                move(x() + delta.x(), y() + delta.y()); // 根据鼠标移动的距离来移动窗口
                initialMousePosition = event->globalPos(); // 更新鼠标位置
            }
    }
void reserveHome::mouseReleaseEvent(QMouseEvent *event) {
        if (event->button() == Qt::LeftButton) {
            isDragging = false; // 结束拖动
        }
    }


void reserveHome::on_pushButton_9_clicked()
{
    this->close();
    reserveHome::announcementIsHome = true;
    reserveAnnouncement *announcement = new reserveAnnouncement;
    QString content = "温馨提示："
                      "<ol style='margin-left: 20px;'>"
                      "<li>请勿携带电动车电池、易燃易爆危险物品入馆！</li>"
                      "<li>请勿在馆内使用大功率电器设备！</li>"
                      "</ol>";
    announcement->setContent(content);
    announcement->show();
}

void reserveHome::on_pushButton_8_clicked()
{
    this->close();
    reserveHome::announcementIsHome = true;
    reserveAnnouncement *announcement = new reserveAnnouncement;
    QString content = "温馨提示："
                      "<ol style='margin-left: 20px;'>"
                      "<li>新校区图书馆将于2024年11月16日闭关修缮，预计11月20日开放。</li>"
                      "</ol>";
    announcement->setContent(content);
    announcement->show();
}

void reserveHome::on_pushButton_7_clicked()
{
    this->close();
    reserveHome::announcementIsHome = true;
    reserveAnnouncement *announcement = new reserveAnnouncement;
    QString content = "温馨提示："
                      "<ol style='margin-left: 20px;'>"
                      "<li>近期天气变冷，图书馆将开发热空调使用。</li>"
                      "<li>请各位同学注意保暖。</li>"
                      "</ol>";
    announcement->setContent(content);
    announcement->show();
}

void reserveHome::on_pushButton_10_clicked()
{
    this->close();
    reservecheck *r = new reservecheck;
    r->show();
}

void reserveHome::on_pushButton_6_clicked()
{
    this->close();
    announcement* a = new announcement;
    a->show();
}
void reserveHome::saveCampusesToJson(campus campuses[], const QString &fileName) {
    QJsonArray campusesArray;
    for (int i = 0; i < 4; ++i) {
        QJsonObject campusObj;
        campusObj["name"] = campuses[i].name;
        campusObj["floorNum"] = campuses[i].floorNum;

        QJsonArray floorsArray;
        for (int j = 0; j < campuses[i].floorNum; ++j) {
            QJsonObject floorObj;
            floorObj["name"] = campuses[i].f[j].name;
            floorObj["areaNum"] = campuses[i].f[j].areaNum;

            QJsonArray areasArray;
            for (int k = 0; k < campuses[i].f[j].areaNum; ++k) {
                QJsonObject areaObj;
                areaObj["name"] = campuses[i].f[j].a[k].name;
                areaObj["seatNum"] = campuses[i].f[j].a[k].seatNum;

                QJsonArray seatsArray;
                for (int l = 0; l < campuses[i].f[j].a[k].seatNum; ++l) {
                    QJsonObject seatObj;
                    seatObj["name"] = campuses[i].f[j].a[k].s[l].name;
                    seatObj["isUnbooked"] = campuses[i].f[j].a[k].s[l].isUnbooked;
                    seatsArray.append(seatObj);
                }
                areaObj["s"] = seatsArray;
                areasArray.append(areaObj);
            }
            floorObj["a"] = areasArray;
            floorsArray.append(floorObj);
        }
        campusObj["f"] = floorsArray;
        campusesArray.append(campusObj);
    }

    QJsonObject rootObj;
    rootObj["campuses"] = campusesArray;

    QJsonDocument doc(rootObj);
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.write(doc.toJson());
        file.close();
        std::cout << "JSON file saved successfully." << std::endl;
    } else {
        std::cerr << "Could not open file for writing." << std::endl;
    }
}

void reserveHome::importJsonToCampuses(const QString &fileName,campus campuses[]) {
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        std::cerr << "Could not open file" << std::endl;
        return;
    }
    QByteArray data = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        std::cerr << "Invalid JSON" << std::endl;
        return;
    }
    QJsonObject root = doc.object();
    QJsonArray campusesArray = root["campuses"].toArray();

    for (int i = 0; i < campusesArray.size() && i < 4; ++i) {
        QJsonObject campusObj = campusesArray[i].toObject();
        campuses[i].name = campusObj["name"].toString();
        campuses[i].floorNum = campusObj["floorNum"].toInt();
        campuses[i].f = new floor[campuses[i].floorNum];

        QJsonArray floorsArray = campusObj["f"].toArray();
        for (int j = 0; j < floorsArray.size() && j < campuses[i].floorNum; ++j) {
            QJsonObject floorObj = floorsArray[j].toObject();
            campuses[i].f[j].name = floorObj["name"].toString();
            campuses[i].f[j].areaNum = floorObj["areaNum"].toInt();
            campuses[i].f[j].a = new area[campuses[i].f[j].areaNum];

            QJsonArray areasArray = floorObj["a"].toArray();
            for (int k = 0; k < areasArray.size() && k < campuses[i].f[j].areaNum; ++k) {
                QJsonObject areaObj = areasArray[k].toObject();
                campuses[i].f[j].a[k].name = areaObj["name"].toString();
                campuses[i].f[j].a[k].seatNum = areaObj["seatNum"].toInt();
                campuses[i].f[j].a[k].s = new seat[campuses[i].f[j].a[k].seatNum];

                QJsonArray seatsArray = areaObj["s"].toArray();
                for (int l = 0; l < seatsArray.size() && l < campuses[i].f[j].a[k].seatNum; ++l) {
                    QJsonObject seatObj = seatsArray[l].toObject();
                    campuses[i].f[j].a[k].s[l].name = seatObj["name"].toString();
                    campuses[i].f[j].a[k].s[l].isUnbooked = seatObj["isUnbooked"].toBool();
                }
            }
        }
    }
}

void reserveHome::closeEvent(QCloseEvent *event){
    e->close();
    event->accept();
}


int reserveHome::getCampusSeat(int index){
    int result=0;
    campus cam=campuses[index];
    for(int i=0;i<cam.floorNum;i++){
        floor f=cam.f[i];
        for(int j=0;j<f.areaNum;j++){
            area a=f.a[j];
            for(int k=0;k<a.seatNum;k++){
                if(a.s[k].isUnbooked) result++;
            }
        }
    }
    return result;
}
int reserveHome::getFloorSeat(int index){
    int result=0;
    floor f=campuses[index_campus].f[index];
    for(int i=0;i<f.areaNum;i++){
        area a=f.a[i];
        for(int j=0;j<a.seatNum;j++){
            if(a.s[j].isUnbooked) result++;
        }
    }
    return result;
}
int reserveHome::getAreaSeat(int index){
    int result=0;
    area a=campuses[index_campus].f[index_floor].a[index];
    for(int i=0;i<a.seatNum;i++){
        if(a.s[i].isUnbooked) result++;
    }
    return result;
}



